package com.hb.trade.server.project.evaluation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.project.evaluation.dto.*;
import com.hb.core.pojo.project.evaluation.entity.EvaluationCommitteeMembers;
import com.hb.core.pojo.project.evaluation.entity.EvaluationSecond;
import com.hb.core.pojo.project.evaluation.entity.EvaluationThird;
import com.hb.core.pojo.project.evaluation.mapper.EvaluationThirdMapper;
import com.hb.core.pojo.project.evaluation.vo.EvaluationReusableScoreItemVO;
import com.hb.core.pojo.project.evaluation.vo.EvaluationReviewItemResultVO;
import com.hb.core.pojo.project.file.dto.ReviewItemThirdDto;
import com.hb.core.pojo.project.file.entity.ReviewItemSecond;
import com.hb.core.pojo.project.proj.enums.BidWayEnum;
import com.hb.core.pojo.project.section.dto.BidSectionOfferDTO;
import com.hb.core.pojo.project.section.dto.BidSectionTenderDTO;
import com.hb.core.pojo.project.section.entity.BidSectionOffer;
import com.hb.core.pojo.project.section.entity.TradeSecondQuotationBidInfo;
import com.hb.core.pojo.project.section.mapper.BidSectionMapper;
import com.hb.core.pojo.project.section.mapper.BidSectionOfferMapper;
import com.hb.core.pojo.project.section.mapper.BidSectionTenderMapper;
import com.hb.core.pojo.project.section.mapper.TradeSecondQuotationBidInfoMapper;
import com.hb.trade.server.project.evaluation.service.EvaluationCommitteeMembersService;
import com.hb.trade.server.project.evaluation.service.EvaluationSecondService;
import com.hb.trade.server.project.evaluation.service.EvaluationSummaryService;
import com.hb.trade.server.project.evaluation.service.EvaluationThirdService;
import com.hb.trade.server.project.file.service.ReviewItemFirstService;
import com.hb.trade.server.project.file.service.ReviewItemSecondService;
import com.hb.trade.server.project.file.service.ReviewItemThirdService;
import com.hb.trade.server.project.section.service.raw.BidSectionTenderService;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.model.enums.LogicEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.IdUtil;
import org.fzzn.core.util.MsgUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 专家三级评审表 服务实现类
 * </p>
 *
 * @author zhaojk
 * @since 2022-04-13
 */
@Slf4j
@Service
public class EvaluationThirdServiceImpl extends ServiceImpl<EvaluationThirdMapper, EvaluationThird> implements EvaluationThirdService {

    @Resource
    private BidSectionMapper bidSectionMapper;
    @Resource
    private TradeSecondQuotationBidInfoMapper tradeSecondQuotationBidInfoMapper;
    @Resource
    private BidSectionOfferMapper bidSectionOfferMapper;
    @Resource
    private BidSectionTenderMapper bidSectionTenderMapper;

    protected final ReviewItemFirstService reviewItemFirstService;
    protected final ReviewItemSecondService reviewItemSecondService;
    protected final ReviewItemThirdService reviewItemThirdService;
    protected final BidSectionTenderService bidSectionTenderService;
    protected final EvaluationSecondService evaluationSecondService;
    protected final EvaluationCommitteeMembersService evaluationCommitteeMembersService;
    protected final EvaluationSummaryService evaluationSummaryService;

    public EvaluationThirdServiceImpl(ReviewItemSecondService reviewItemSecondService,
                                      ReviewItemThirdService reviewItemThirdService,
                                      BidSectionTenderService bidSectionTenderService,
                                      ReviewItemFirstService reviewItemFirstService,
                                      EvaluationSecondService evaluationSecondService,
                                      EvaluationCommitteeMembersService evaluationCommitteeMembersService,
                                      EvaluationSummaryService evaluationSummaryService) {
        this.reviewItemSecondService = reviewItemSecondService;
        this.reviewItemThirdService = reviewItemThirdService;
        this.bidSectionTenderService = bidSectionTenderService;
        this.reviewItemFirstService = reviewItemFirstService;
        this.evaluationSecondService = evaluationSecondService;
        this.evaluationCommitteeMembersService = evaluationCommitteeMembersService;
        this.evaluationSummaryService = evaluationSummaryService;
    }


    @Override
    public EvaluationReviewItemResultVO allResultOfReviewPoint(EvaluationReviewItemParam evaluationReviewItemParam) {
        Long expertId = evaluationReviewItemParam.getExpertId();
        String expertName = evaluationReviewItemParam.getExpertName();
        Long reviewItemId = evaluationReviewItemParam.getReviewItemId();
        Long sectionId = evaluationReviewItemParam.getSectionId();

        // 组装数据对象
        EvaluationReviewItemResultVO evaluationReviewItemResultVO = new EvaluationReviewItemResultVO();

        List<ReviewItemThirdDto> listReviewItemThirdDto = reviewItemThirdService.selectReviewItemThirdListBySecondReviewItemId(reviewItemId);
        if (listReviewItemThirdDto.size() == 0) {
            return evaluationReviewItemResultVO;
        }

        // 确定表头信息
        List<EvaluationThirdDTO> evaluationThirdDTOList = baseMapper.listByReviewPointIdAndExpertId(sectionId, listReviewItemThirdDto.get(0).getId(), expertId,null);
        List<Map<String, Object>> orgHeaderList = new ArrayList<>();
        for (EvaluationThirdDTO evaluationThirdDTO : evaluationThirdDTOList) {
            Map<String, Object> orgMap = new HashMap<>();
            orgMap.put("orgId", evaluationThirdDTO.getOrgId());
            orgMap.put("orgName", evaluationThirdDTO.getOrgName());
            orgMap.put("tenderPdf", evaluationThirdDTO.getTenderPdf());
            orgHeaderList.add(orgMap);
        }
        evaluationReviewItemResultVO.setOrgHeaderList(orgHeaderList);

        // 组装评审结果map
        List<Map<String, Object>> evaluationResultList = new ArrayList<>();
        for (ReviewItemThirdDto reviewItemThirdDto : listReviewItemThirdDto) {
            Map<String, Object> evaluationResultMap = new HashMap<>();
            evaluationResultMap.put("reviewPointId", reviewItemThirdDto.getId());
            evaluationResultMap.put("reviewPointName", reviewItemThirdDto.getThirdReviewItemName());
            evaluationResultMap.put("reviewPointStandard", reviewItemThirdDto.getAssessStandard());
            evaluationResultMap.put("assess_score", reviewItemThirdDto.getAssessScore());
            evaluationResultMap.put("lowest_score", reviewItemThirdDto.getLowestScore());

            // 评审点是否已提交
            Boolean reviewPointSubmitted = true;
            List<EvaluationThirdDTO> evaluationThirdList = baseMapper.listByReviewPointIdAndExpertId(sectionId, reviewItemThirdDto.getId(), expertId,null);
            for (EvaluationThirdDTO evaluationThirdDTO : evaluationThirdList) {
                Map<String, Object> evaluationMap = new HashMap<>();
                evaluationMap.put("id", evaluationThirdDTO.getId());
                evaluationMap.put("orgId", evaluationThirdDTO.getOrgId());
                evaluationMap.put("finalScore", evaluationThirdDTO.getFinalScore());
                evaluationMap.put("approveFlag", evaluationThirdDTO.getApproveFlag());
                // 如果是定量评审 并且已经打分完成 则标记状态为已打分 （因为前端是拿approveFlag 显示的信息）
                if(evaluationThirdDTO.getReviewMode().equals(1) && StringUtils.isNotEmpty(evaluationThirdDTO.getFinalScore())){
                    evaluationMap.put("approveFlag", 1);
                }
                evaluationMap.put("reviewMode", evaluationThirdDTO.getReviewMode());
                evaluationMap.put("refuseReason", evaluationThirdDTO.getRefuseReason());

                evaluationResultMap.put(Long.toString(evaluationThirdDTO.getOrgId()), evaluationMap);

                // 判断提交状态
                if (!reviewPointSubmitted || evaluationThirdDTO.getEvaluationStatus().equals(0)) {
                    reviewPointSubmitted = false;
                }
            }

            evaluationResultMap.put("submitFlag", reviewPointSubmitted ? 1 : 0);
            evaluationResultList.add(evaluationResultMap);
        }
        evaluationReviewItemResultVO.setEvaluationResultList(evaluationResultList);

        return evaluationReviewItemResultVO;
    }

    @Override
    public List<EvaluationThirdDTO> resultOfReviewPoint(Long sectionId, Long reviewPointId, Long expertId) {
        List<EvaluationThirdDTO> listEvaluationThirdDto = baseMapper.listByReviewPointIdAndExpertId(sectionId, reviewPointId, expertId,null);
        return listEvaluationThirdDto;
    }

    @Override
    public List<EvaluationThirdDTO> resultOfReviewPoint(Long sectionId, Long secondReviewItemId) {
        List<EvaluationThirdDTO> listEvaluationThirdDto = baseMapper.listByReviewPointIdAndExpertId(sectionId, null, null,secondReviewItemId);
        return listEvaluationThirdDto;
    }

    @Override
    public List<EvaluationThirdDTO> listEvaluationThirdDTO(Long sectionId, Long secondReviewItemId, Integer firstReviewItemType) {
        List<EvaluationThirdDTO> listEvaluationThirdDto = baseMapper.listEvaluationThirdDTO(sectionId, secondReviewItemId, firstReviewItemType);
        return listEvaluationThirdDto;
    }

    @Override
    public Boolean evaluationThirdHaveSummaryData(List<Long> idList) {
        Integer count = baseMapper.evaluationThirdHaveSummaryData(idList);
        if (count > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean batchPass(List<EvaluationSubmitScoreParam> evaluationSubmitScoreParamList) {
        return batchPassOrRefuse(evaluationSubmitScoreParamList, true);
    }

    @Override
    public Boolean batchRefuse(List<EvaluationSubmitScoreParam> evaluationSubmitScoreParamList) {
        return batchPassOrRefuse(evaluationSubmitScoreParamList, false);
    }

    private Boolean batchPassOrRefuse(List<EvaluationSubmitScoreParam> evaluationSubmitScoreParamList, Boolean isPass) {
        List<EvaluationThird> listEvaluationThird = new ArrayList<>();
        for (EvaluationSubmitScoreParam evaluationSubmitScoreParam : evaluationSubmitScoreParamList) {
            EvaluationThird evaluationThird = BeanUtil.copyProperties(evaluationSubmitScoreParam, EvaluationThird.class);
            if (evaluationThird.getId() == null) {
                evaluationThird.buildBaseData(1);
            } else {
                evaluationThird.buildBaseData(2);
            }

            // 批量操作之后状态变为未提交
            evaluationThird.setEvaluationStatus(0);

            // 是否通过
            if (isPass) {
                evaluationThird.setApproveFlag(LogicEnum.YES.getCode());
            } else {
                evaluationThird.setApproveFlag(LogicEnum.NO.getCode());
            }

            listEvaluationThird.add(evaluationThird);
        }

        Boolean save = this.saveOrUpdateBatch(listEvaluationThird);

        return save;
    }

    @Override
    public Boolean saveScoreOfReviewPointSingleOrg(EvaluationSubmitScoreParam evaluationSubmitScoreParam) {
        EvaluationThird evaluationThird = BeanUtil.copyProperties(evaluationSubmitScoreParam, EvaluationThird.class);
        if (evaluationThird.getId() == null) {
            evaluationThird.buildBaseData(1);
        } else {
            evaluationThird.buildBaseData(2);
        }

        // 保存之后状态变为未提交
        evaluationThird.setEvaluationStatus(0);

        return this.saveOrUpdate(evaluationThird);
    }

    @Override
    public Boolean saveScoreBatch(List<EvaluationSubmitScoreParam> evaluationSubmitScoreParamList) {
        List<EvaluationThird> listEvaluationThird = new ArrayList<>();
        for (EvaluationSubmitScoreParam evaluationSubmitScoreParam : evaluationSubmitScoreParamList) {
            EvaluationThird evaluationThird = BeanUtil.copyProperties(evaluationSubmitScoreParam, EvaluationThird.class);
            if (evaluationThird.getId() == null) {
                evaluationThird.buildBaseData(1);
            } else {
                evaluationThird.buildBaseData(2);
            }

            // 批量保存之后状态变为未提交
            evaluationThird.setEvaluationStatus(0);

            listEvaluationThird.add(evaluationThird);
        }

        return this.saveOrUpdateBatch(listEvaluationThird);
    }

    @Override
    public Boolean submitScoreOfReviewPoint(List<EvaluationSubmitScoreParam> evaluationSubmitScoreParamList) {
        return submitScoreOfReviewPoint(evaluationSubmitScoreParamList, false);
    }

    @Override
    public Boolean submitAndShareScoreOfReviewPoint(List<EvaluationSubmitScoreParam> evaluationSubmitScoreParamList) {
        return submitScoreOfReviewPoint(evaluationSubmitScoreParamList, true);
    }

    private Boolean submitScoreOfReviewPoint(List<EvaluationSubmitScoreParam> evaluationSubmitScoreParamList, Boolean isShare) {
        List<EvaluationThird> listEvaluationThird = new ArrayList<>();
        for (EvaluationSubmitScoreParam evaluationSubmitScoreParam : evaluationSubmitScoreParamList) {
            EvaluationThird evaluationThird = BeanUtil.copyProperties(evaluationSubmitScoreParam, EvaluationThird.class);
            if (evaluationThird.getId() == null) {
                evaluationThird.buildBaseData(1);
            } else {
                evaluationThird.buildBaseData(2);
            }

            // 提交上来的默认都是打过分的
            evaluationThird.setEvaluationStatus(1);

            // 是否共享
            if (isShare) {
                evaluationThird.setShareFlag(LogicEnum.YES.getCode());
            }

            listEvaluationThird.add(evaluationThird);
        }

        Boolean save = this.saveOrUpdateBatch(listEvaluationThird);

        // 更新二级汇总表
        Boolean secondSummary = true;
        if (evaluationSubmitScoreParamList.size() > 0) {
            EvaluationSubmitScoreParam evaluation = evaluationSubmitScoreParamList.get(0);
            EvaluationThird evaluationThird = getById(evaluation.getId());

            secondSummary = this.calculateResultOfSecondReviewItem(evaluationThird.getSectionId(), evaluationThird.getSecondReviewItemId());
        }

        return save && secondSummary;
    }

    @Override
    public Boolean submitScoreOfReviewItem(List<EvaluationSubmitScoreParam> evaluationSubmitScoreParamList) {
        return submitScoreOfReviewPoint(evaluationSubmitScoreParamList, false);
    }

    /**
     * 修改二级，三级 报价评审的状态为待评审
     *
     * @param evaluationThirdId 三级评审id
     * @author tian
     * @date 2022-4-23 11:32
     */
    @Override
    @Transactional
    public void editEvaluationStatusByOfferReview(Long evaluationThirdId) {
        // 获取三级评审项的详情
        EvaluationThird evaluationThird = baseMapper.selectById(evaluationThirdId);

        // 修改三级评审项状态为待评审
        baseMapper.editEvaluationStatus(evaluationThird.getSectionId(), evaluationThird.getSecondReviewItemId(), 0);

        // 修改二级评审项状态为待评审
        evaluationSecondService.initialResultSummary(evaluationThird.getSectionId(), evaluationThird.getSecondReviewItemId());
    }

    /**
     * 动态计算评审项的汇总结果
     *
     * @param secondReviewItemId
     * @return
     */
    private Boolean calculateResultOfSecondReviewItem(Long sectionId, Long secondReviewItemId) {
        ReviewItemSecond reviewItemSecond = reviewItemSecondService.getById(secondReviewItemId);
        int reviewMode = reviewItemSecond.getReviewMode();

        List<Long> orgIdList = baseMapper.findOrgIdListNoEliminate(sectionId, secondReviewItemId);
        for (Long orgId : orgIdList) {
            // 专家列表
            List<EvaluationCommitteeMembers> expertList = evaluationCommitteeMembersService.selectCommitteeMembersBySectionId(sectionId, null);
            for (EvaluationCommitteeMembers expert : expertList) {
                EvaluationThird sqlParam = new EvaluationThird();
                sqlParam.setSectionId(sectionId);
                sqlParam.setSecondReviewItemId(secondReviewItemId);
                sqlParam.setExpertId(expert.getId());
                sqlParam.setOrgId(orgId);

                List<EvaluationThird> evaluationThirdList = baseMapper.findEvaluationThirdList(sqlParam);
                if (evaluationThirdList.size() == 0) {
                    continue;
                }

                // 判断是否可对汇总
                boolean canSummary = true;
                for (EvaluationThird evaluationThird : evaluationThirdList) {
                    if (evaluationThird.getEvaluationStatus().equals(0)) {
                        canSummary = false;
                        break;
                    }
                    if (reviewMode == 1) {
                        // 定量
                        if (evaluationThird.getFinalScore() == null) {
                            canSummary = false;
                            break;
                        }
                    } else if (reviewMode == 2) {
                        // 定性
                        if (evaluationThird.getApproveFlag() == null) {
                            canSummary = false;
                            break;
                        }
                    }
                }
                // 不可汇总
                if (!canSummary) {
                    continue;
                }

                // 汇总结果
                int summaryApproveFlag = LogicEnum.YES.getCode();
                Double summaryScore = 0.0;
                for (EvaluationThird evaluationThird : evaluationThirdList) {
                    if (reviewMode == 1) {
                        // 定量
                        summaryScore += Double.parseDouble(evaluationThird.getFinalScore());
                    } else if (reviewMode == 2) {
                        // 定性
                        if (evaluationThird.getApproveFlag().equals(LogicEnum.NO.getCode())) {
                            summaryApproveFlag = LogicEnum.NO.getCode();
                            break;
                        }
                    }
                }

                EvaluationSecond updateSecond = new EvaluationSecond();
                updateSecond.setSectionId(sectionId);
                updateSecond.setSecondReviewItemId(secondReviewItemId);
                updateSecond.setOrgId(orgId);
                updateSecond.setExpertId(expert.getId());

                if (reviewMode == 1) {
                    // 定量
                    updateSecond.setFinalScore(summaryScore);
                    evaluationSecondService.updateFinalScoreByExpertIdAndSecondReviewItemId(updateSecond);
                } else if (reviewMode == 2) {
                    // 定性
                    updateSecond.setApproveFlag(summaryApproveFlag);
                    evaluationSecondService.updateApproveFlagByExpertIdAndSecondReviewItemId(updateSecond);
                }

            }
        }

        return true;
    }

    @Override
    public List<EvaluationReusableScoreItemVO> reusableScoreOfReviewPoint(EvaluationReviewPointParam evaluationReviewPointParam) {
        Long reviewPointId = evaluationReviewPointParam.getReviewPointId();
        Long sectionId = evaluationReviewPointParam.getSectionId();
        List<EvaluationThirdDTO> evaluationThirdDTOList = baseMapper.findFinishedScoreAndShareBySectionIdAndThirdReviewItemId(sectionId, reviewPointId);

        List<EvaluationReusableScoreItemVO> evaluationReusableScoreItemList = new ArrayList<>();
        if (evaluationThirdDTOList.size() == 0) {
            return evaluationReusableScoreItemList;
        }

        // 先判断是定性还是定量，来区分对比的字段
        int reviewMode = evaluationThirdDTOList.get(0).getReviewMode();

        // 对同一个的打分结果拼接为一个字符串，组成map进行对比
        // 对比的map
        Map<Long, String> compareMap = new HashMap<>();
        // 专家id和姓名的map
        Map<Long, String> expertMap = new HashMap<>();
        // 专家打分的map
        Map<Long, List<EvaluationThirdDTO>> expertEvaluation = new HashMap<>();

        for (EvaluationThirdDTO evaluationThirdDTO : evaluationThirdDTOList) {
            Long expertId = evaluationThirdDTO.getExpertId();
            String expertName = evaluationThirdDTO.getExpertName();
            expertMap.put(expertId, expertName);

            // 专家打分的map
            if (expertEvaluation.get(expertId) == null) {
                List<EvaluationThirdDTO> expertEvaluationThirdDTOList = new ArrayList<>();
                expertEvaluation.put(expertId, expertEvaluationThirdDTOList);
            }
            expertEvaluation.get(expertId).add(evaluationThirdDTO);

            // 对比的map
            String score = "";
            if (reviewMode == 1) {
                // 定量
                score = evaluationThirdDTO.getFinalScore();
            } else if (reviewMode == 2) {
                // 定性
                score = evaluationThirdDTO.getApproveFlag().toString();
            }
            String combineScore = compareMap.get(expertId);
            if (StrUtil.isBlank(combineScore)) {
                combineScore = score;
            } else {
                combineScore = combineScore + score;
            }
            compareMap.put(expertId, combineScore);
        }

        // 反转map, key作为value，value作为key
        Map<String, List<Long>> reversedMap = new HashMap<>();
        for (Map.Entry<Long, String> entry : compareMap.entrySet()) {
            if (reversedMap.get(entry.getValue()) == null) {
                List<Long> expertList = new ArrayList<>();
                reversedMap.put(entry.getValue(), expertList);
            }
            reversedMap.get(entry.getValue()).add(entry.getKey());
        }

        // 组装返回结果
        int num = 1;
        for (Map.Entry<String, List<Long>> entry : reversedMap.entrySet()) {
            EvaluationReusableScoreItemVO evaluationReusableScoreItemVO = new EvaluationReusableScoreItemVO();
            // 序号
            evaluationReusableScoreItemVO.setNum(num);

            // 专家信息
            Map<Long, String> reusableExpertMap = new HashMap<>();
            List<Long> expertList = entry.getValue();
            for (Long expertId : expertList) {
                reusableExpertMap.put(expertId, expertMap.get(expertId));
            }
            evaluationReusableScoreItemVO.setExpertInfoMap(reusableExpertMap);

            // 企业评审结果列表
            evaluationReusableScoreItemVO.setEvaluationThirdDTOList(expertEvaluation.get(entry.getValue().get(0)));

            evaluationReusableScoreItemList.add(evaluationReusableScoreItemVO);
            num++;
        }

        log.info("可复用数据：{}", evaluationReusableScoreItemList.toString());

        return evaluationReusableScoreItemList;
    }

    @Override
    public Boolean confirmResultSummary(EvaluationReviewItemParam evaluationReviewItemParam) {
        Long sectionId = evaluationReviewItemParam.getSectionId();
        Long reviewItemId = evaluationReviewItemParam.getReviewItemId();

        baseMapper.editEvaluationStatus(sectionId, reviewItemId, 2);

        return true;
    }

    @Override
    public Boolean recheckResultSummary(Long sectionId, Long reviewItemId) {
        baseMapper.editEvaluationStatus(sectionId, reviewItemId, 1);

        return true;
    }

    /**
     * 查询报价评审
     * @author tian
     * @date 2022-4-20 15:09
     * @param evaluationReviewItemParam
     * @return org.fzzn.core.model.msg.Message<java.util.Map>
     */
    @Override
    @Transactional
    public Message<Map> findQuotationReview(EvaluationReviewItemParam evaluationReviewItemParam) {
        Map result = new HashMap();

        // 二级评审项id
        Long reviewItemId = evaluationReviewItemParam.getReviewItemId();
        // 标段id
        Long sectionId = evaluationReviewItemParam.getSectionId();

        // 如果存在多轮报价  查询多轮报价是否结束
        Integer bidWay = bidSectionMapper.selectBidWayBySectionId(sectionId);
        if (bidWay.equals(BidWayEnum.NEG.getCode()) || bidWay.equals(BidWayEnum.CON.getCode())) {
            // 查询多伦报价是否完成
            QueryWrapper<TradeSecondQuotationBidInfo> secondQuotationBidInfoQueryWrapper = new QueryWrapper<>();
            secondQuotationBidInfoQueryWrapper.lambda().eq(TradeSecondQuotationBidInfo::getSectionId, sectionId)
                    .eq(TradeSecondQuotationBidInfo::getEndType, "2");

            List<TradeSecondQuotationBidInfo> tradeSecondQuotationBidInfos = tradeSecondQuotationBidInfoMapper.selectList(secondQuotationBidInfoQueryWrapper);

            if(CollUtil.isEmpty(tradeSecondQuotationBidInfos)){
                result.put("againOfferEnd", false);
                return MsgUtil.success(result);
            }
        }

        // 查询组长的评审信息（因为只要组长才会对报价进行打分）
        List<EvaluationCommitteeMembers> expertList = evaluationCommitteeMembersService.selectCommitteeMembersBySectionId(sectionId, "1");

        if (CollUtil.isEmpty(expertList)) {
            return MsgUtil.fail("未获取到组长信息");
        }

        // 查询当前报价评审项下的评审点
        List<ReviewItemThirdDto> thirdReviewItemList = reviewItemThirdService.selectReviewItemThirdListBySecondReviewItemId(reviewItemId);
        if (CollUtil.isEmpty(thirdReviewItemList)) {
            return MsgUtil.fail("未查询到报价评审项");
        }

        // 如果存在信息则直接返回
        List<EvaluationThirdDTO> evaluationThirdDTOList = baseMapper.listByReviewPointIdAndExpertId(sectionId, thirdReviewItemList.get(0).getId(), expertList.get(0).getId(),null);
        if (CollUtil.isNotEmpty(evaluationThirdDTOList)) {
            result = assembleData(evaluationThirdDTOList, thirdReviewItemList.get(0));

            // 查询组长是否对报价评审确认
            Integer evaluationStatus = evaluationSecondService.countByEvaluationStatus(expertList.get(0).getId(), evaluationReviewItemParam.getSectionId(), evaluationReviewItemParam.getReviewItemId());

            result.put("evaluationStatus", evaluationStatus);
            result.put("againOfferEnd", true);
            return MsgUtil.success(result);
        }

        List<EvaluationThirdDTO> evaluationThirdDTOs;

        // 如果是竞争性谈判，竞争性磋商需要多伦报价
        if (bidWay.equals(BidWayEnum.NEG.getCode()) || bidWay.equals(BidWayEnum.CON.getCode())) {
            evaluationThirdDTOs = saveThirdReviewItemByDuolunQuotation(sectionId, thirdReviewItemList.get(0));
            if (CollUtil.isEmpty(evaluationThirdDTOs)) {
                return MsgUtil.fail("多伦报价未结束，请先结束多伦报价");
            }

        } else {
            // 直接查询投标报价
            evaluationThirdDTOs = saveThirdReviewItemByQuotation(sectionId, thirdReviewItemList.get(0));
            if (CollUtil.isEmpty(evaluationThirdDTOs)) {
                return MsgUtil.fail("未查询到投标人的报价信息");
            }
        }

        // 查询数据库中组长的数据，组装信息返回
        List<EvaluationThirdDTO> orgReviewList = baseMapper.listByReviewPointIdAndExpertId(sectionId, thirdReviewItemList.get(0).getId(), expertList.get(0).getId(),null);
        result = assembleData(orgReviewList, thirdReviewItemList.get(0));

        // 因为是新增的数据 则直接标记当前状态为 未评审
        // 状态 0，未评审，1，已评审，2，已汇总
        result.put("evaluationStatus", 0);

        result.put("againOfferEnd", true);
        return MsgUtil.success(result);
    }


    /**
     * 保存多伦报价信息
     *
     * @author tian
     * @date 2022-4-20 11:11
     */
    public List<EvaluationThirdDTO> saveThirdReviewItemByDuolunQuotation(Long sectionId, ReviewItemThirdDto reviewItemThirdDto) {
        // 返回组长的信息
        List<EvaluationThirdDTO> evaluationThirdDTOList = new ArrayList<>();

        // 查询多伦报价是否完成
        QueryWrapper<TradeSecondQuotationBidInfo> secondQuotationBidInfoQueryWrapper = new QueryWrapper<>();
        secondQuotationBidInfoQueryWrapper.lambda().eq(TradeSecondQuotationBidInfo::getSectionId, sectionId)
                .eq(TradeSecondQuotationBidInfo::getEndType, "2");

        List<TradeSecondQuotationBidInfo> tradeSecondQuotationBidInfos = tradeSecondQuotationBidInfoMapper.selectList(secondQuotationBidInfoQueryWrapper);
        // 如果多伦报价结束则存库
        if (CollUtil.isNotEmpty(tradeSecondQuotationBidInfos)) {
            Long secBidId = tradeSecondQuotationBidInfos.get(0).getId();

            // 查询最后一轮的报价
            List<BidSectionOfferDTO> bidSectionOfferList = bidSectionOfferMapper.selectParamValueBySecBidId(Integer.valueOf(secBidId.toString()));

            if (CollUtil.isNotEmpty(bidSectionOfferList)) {
                // 保存多伦报价
                List<EvaluationCommitteeMembers> expertList = evaluationCommitteeMembersService.selectCommitteeMembersBySectionId(sectionId, null);

                EvaluationSecond evaluationSecond;
                EvaluationThird evaluationThird;

                for (BidSectionOfferDTO bidSectionOffer : bidSectionOfferList) {
                    // 查询公司是否淘汰
                    Integer num = baseMapper.countBySectionIdAndOrgIdAndEliminateFlag(sectionId, bidSectionOffer.getOrgId());
                    Integer evaluationStatus = num > 0 ? 1 : 2;

                    for (EvaluationCommitteeMembers expert : expertList) {
                        // 提前保存二级汇总信息
                        evaluationSecond = new EvaluationSecond();
                        evaluationSecond.setId(IdUtil.getId());
                        evaluationSecond.setFileId(reviewItemThirdDto.getFileId());
                        evaluationSecond.setSecondReviewItemId(reviewItemThirdDto.getSecondReviewItemId());
                        evaluationSecond.setSectionId(sectionId);
                        evaluationSecond.setExpertId(expert.getId());
                        evaluationSecond.setExpertName(expert.getMemberName());
                        evaluationSecond.setOrgId(bidSectionOffer.getOrgId());
                        evaluationSecond.setOrgName(bidSectionOffer.getOrgName());
                        evaluationSecond.setReviewMode(1);
                        evaluationSecond.setEliminateFlag(evaluationStatus);
                        evaluationSecond.setCreateTime(LocalDateTime.now());
                        evaluationSecondService.save(evaluationSecond);

                        // 提前保存三级级汇总信息
                        evaluationThird = new EvaluationThird();
                        evaluationThird.setId(IdUtil.getId());
                        evaluationThird.setFileId(reviewItemThirdDto.getFileId());
                        evaluationThird.setSecondReviewItemId(reviewItemThirdDto.getSecondReviewItemId());
                        evaluationThird.setThirdReviewItemId(reviewItemThirdDto.getId());
                        evaluationThird.setSectionId(sectionId);
                        evaluationThird.setExpertId(expert.getId());
                        evaluationThird.setExpertName(expert.getMemberName());
                        evaluationThird.setOrgId(bidSectionOffer.getOrgId());
                        evaluationThird.setOrgName(bidSectionOffer.getOrgName());
                        evaluationThird.setReviewMode(1);
                        evaluationThird.setQuotedPrice(bidSectionOffer.getParamValue());
                        evaluationThird.setEliminateFlag(evaluationStatus);
                        evaluationThird.setCreateId(expert.getId());
                        evaluationThird.setCreateTime(LocalDateTime.now());
                        baseMapper.insert(evaluationThird);

                        // 添加组长的评审信息
                        if (expert.getChairmanFlag().equals(1)) {
                            EvaluationThirdDTO evaluationThirdDTO1 = new EvaluationThirdDTO();
                            BeanUtils.copyProperties(evaluationThird, evaluationThirdDTO1);
                            evaluationThirdDTOList.add(evaluationThirdDTO1);
                        }
                    }
                }

            }
        }
        return evaluationThirdDTOList;
    }


    /**
     * 保存报价信息
     *
     * @author tian
     * @date 2022-4-20 11:11
     */
    public List<EvaluationThirdDTO> saveThirdReviewItemByQuotation(Long sectionId, ReviewItemThirdDto reviewItemThirdDto) {
        // 返回组长的信息
        List<EvaluationThirdDTO> evaluationThirdDTOList = new ArrayList<>();

        // 查询解密成功的企业
        List<BidSectionTenderDTO> bidSectionTenderDTOS = bidSectionTenderMapper.listDecryptionBidSectionTender(sectionId, 1,    1);

        if (CollUtil.isNotEmpty(bidSectionTenderDTOS)) {
            List<EvaluationCommitteeMembers> expertList = evaluationCommitteeMembersService.selectCommitteeMembersBySectionId(sectionId, null);

            EvaluationSecond evaluationSecond;
            EvaluationThird evaluationThird;

            // 保存每个专家的评审信息
            for (BidSectionTenderDTO bidSectionTenderDTO : bidSectionTenderDTOS) {
                JSONObject jsonObject = JSONUtil.parseObj(bidSectionTenderDTO.getDecryptContent());
                BigDecimal quotedPrice = new BigDecimal("0");
                if (null != jsonObject && jsonObject.containsKey("投标报价小写（元）")) {
                    quotedPrice = jsonObject.get("投标报价小写（元）", BigDecimal.class);
                }

                // 查询公司是否淘汰
                Integer num = baseMapper.countBySectionIdAndOrgIdAndEliminateFlag(sectionId, bidSectionTenderDTO.getOrgId());
                Integer evaluationStatus = num > 0 ? 1 : 2;

                for (EvaluationCommitteeMembers expert : expertList) {
                    // 提前保存二级汇总信息
                    evaluationSecond = new EvaluationSecond();
                    evaluationSecond.setId(IdUtil.getId());
                    evaluationSecond.setFileId(reviewItemThirdDto.getFileId());
                    evaluationSecond.setSecondReviewItemId(reviewItemThirdDto.getSecondReviewItemId());
                    evaluationSecond.setSectionId(sectionId);
                    evaluationSecond.setExpertId(expert.getId());
                    evaluationSecond.setExpertName(expert.getMemberName());
                    evaluationSecond.setOrgId(bidSectionTenderDTO.getOrgId());
                    evaluationSecond.setOrgName(bidSectionTenderDTO.getOrgName());
                    evaluationSecond.setReviewMode(1);
                    evaluationSecond.setEliminateFlag(evaluationStatus);
                    evaluationSecond.setCreateTime(LocalDateTime.now());
                    evaluationSecondService.save(evaluationSecond);

                    // 提前保存三级级汇总信息
                    evaluationThird = new EvaluationThird();
                    evaluationThird.setId(IdUtil.getId());
                    evaluationThird.setFileId(reviewItemThirdDto.getFileId());
                    evaluationThird.setSecondReviewItemId(reviewItemThirdDto.getSecondReviewItemId());
                    evaluationThird.setThirdReviewItemId(reviewItemThirdDto.getId());
                    evaluationThird.setSectionId(sectionId);
                    evaluationThird.setExpertId(expert.getId());
                    evaluationThird.setExpertName(expert.getMemberName());
                    evaluationThird.setOrgId(bidSectionTenderDTO.getOrgId());
                    evaluationThird.setOrgName(bidSectionTenderDTO.getOrgName());
                    evaluationThird.setReviewMode(1);
                    evaluationThird.setQuotedPrice(quotedPrice.toString());
                    evaluationThird.setEliminateFlag(evaluationStatus);
                    evaluationThird.setCreateId(expert.getId());
                    evaluationThird.setCreateTime(LocalDateTime.now());
                    baseMapper.insert(evaluationThird);

                    // 添加组长的评审信息
                    if (expert.getChairmanFlag().equals(1)) {
                        EvaluationThirdDTO evaluationThirdDTO1 = new EvaluationThirdDTO();
                        BeanUtils.copyProperties(evaluationThird, evaluationThirdDTO1);
                        evaluationThirdDTOList.add(evaluationThirdDTO1);
                    }
                }
            }
        }
        return evaluationThirdDTOList;
    }


    /**
     * 组装数据
     *
     * @param orgReviewList
     * @return java.util.Map
     * @author tian
     * @date 2022-4-20 15:08
     */
    public Map assembleData(List<EvaluationThirdDTO> orgReviewList, ReviewItemThirdDto reviewItemThirdDto) {
        Map result = new HashMap();

        List<Map> orgList = new ArrayList<>();
        List<Map> dataList = new ArrayList<>();
        Map org;
        Map offer;
        Map score;
        Map offerInfo = new HashMap();
        offerInfo.put("name", "报价（元）");

        Map scoreInfo = new HashMap();
        scoreInfo.put("name", "得分（" + reviewItemThirdDto.getAssessScore() + "）");
        // 当前得分分值
        scoreInfo.put("assessScore", reviewItemThirdDto.getAssessScore());
        for (EvaluationThirdDTO evaluationThirdDTO : orgReviewList) {

            // 组装企业信息
            org = new HashMap();
            org.put("orgId", evaluationThirdDTO.getOrgId());
            org.put("orgName", evaluationThirdDTO.getOrgName());
            orgList.add(org);

            // 组装报价信息
            offer = new HashMap();
            offer.put("finalScore", evaluationThirdDTO.getQuotedPrice());
            offerInfo.put(evaluationThirdDTO.getOrgId(), offer);


            score = new HashMap();
            score.put("id", evaluationThirdDTO.getId());
            String finalScore = "";
            if(StrUtil.isNotEmpty(evaluationThirdDTO.getFinalScore())){
                finalScore = evaluationThirdDTO.getFinalScore();
            }
            score.put("finalScore", finalScore);
            scoreInfo.put(evaluationThirdDTO.getOrgId(), score);
        }
        dataList.add(offerInfo);
        dataList.add(scoreInfo);

        result.put("orgList", orgList);
        result.put("dataList", dataList);
        return result;
    }


    /**
     * 非组长 确认报价
     * @author tian
     * @date 2022-4-20 15:36
     * @param evaluationReviewItemParam
     * @return org.fzzn.core.model.msg.Message<java.lang.String>
     */
    @Override
    public Message<String> confirmOffer(EvaluationReviewItemParam evaluationReviewItemParam) {
        Long sectionId = evaluationReviewItemParam.getSectionId();
        Long reviewItemId = evaluationReviewItemParam.getReviewItemId();

        // 查询当前评审项是否已汇总
        Integer num = reviewItemSecondService.countBySecondReviewItemIdAndEvaluationStatus(reviewItemId, sectionId);
        if (num > 0) {
            return MsgUtil.fail("当前节点已经汇总，请刷新界面");
        }

        // 查询组长的评审信息（因为只要组长才会对报价进行打分）
        List<EvaluationCommitteeMembers> expertList = evaluationCommitteeMembersService.selectCommitteeMembersBySectionId(sectionId, "1");

        if (CollUtil.isEmpty(expertList)) {
            return MsgUtil.fail("未获取到组长信息");
        }

        // 查询当前报价评审项下的评审点
        List<ReviewItemThirdDto> thirdReviewItemList = reviewItemThirdService.selectReviewItemThirdListBySecondReviewItemId(reviewItemId);
        if (CollUtil.isEmpty(thirdReviewItemList)) {
            return MsgUtil.fail("未查询到报价评审项");
        }

        // 查询组长的二级打分记录
        QueryWrapper<EvaluationSecond> evaluationSecondQueryWrapper = new QueryWrapper<>();
        evaluationSecondQueryWrapper.lambda().eq(EvaluationSecond::getExpertId, expertList.get(0).getId())
                .eq(EvaluationSecond::getSectionId, sectionId)
                .eq(EvaluationSecond::getSecondReviewItemId, reviewItemId);

        List<EvaluationSecond> evaluationSecondList = evaluationSecondService.list(evaluationSecondQueryWrapper);

        // 查询组长的三级打分记录
        QueryWrapper<EvaluationThird> evaluationThirdQueryWrapper = new QueryWrapper<>();
        evaluationThirdQueryWrapper.lambda().eq(EvaluationThird::getExpertId, expertList.get(0).getId())
                .eq(EvaluationThird::getSectionId, sectionId)
                .eq(EvaluationThird::getThirdReviewItemId, thirdReviewItemList.get(0).getId());

        List<EvaluationThird> evaluationThirdList = baseMapper.selectList(evaluationThirdQueryWrapper);


        if (CollUtil.isEmpty(evaluationSecondList) || CollUtil.isEmpty(evaluationThirdList)) {
            return MsgUtil.fail("未查询到组长的报价得分信息");
        }

        // 修改二级评审因素的打分
        EvaluationSecond updateSecond;
        for (EvaluationSecond evaluationSecond : evaluationSecondList) {
            updateSecond = new EvaluationSecond();
            updateSecond.setOrgId(evaluationSecond.getOrgId());
            // 当前登录的专家
            updateSecond.setExpertId(evaluationReviewItemParam.getExpertId());
            updateSecond.setSectionId(evaluationSecond.getSectionId());
            updateSecond.setSecondReviewItemId(evaluationSecond.getSecondReviewItemId());
            updateSecond.setFinalScore(evaluationSecond.getFinalScore());
            evaluationSecondService.updateFinalScoreByExpertIdAndSecondReviewItemId(updateSecond);
        }

        // 修改三级评审因素的打分
        EvaluationThird updateThird;
        for (EvaluationThird evaluationThird : evaluationThirdList) {
            updateThird = new EvaluationThird();
            updateThird.setOrgId(evaluationThird.getOrgId());
            // 当前登录的专家
            updateThird.setExpertId(evaluationReviewItemParam.getExpertId());
            updateThird.setSectionId(evaluationThird.getSectionId());
            updateThird.setThirdReviewItemId(evaluationThird.getThirdReviewItemId());
            updateThird.setFinalScore(evaluationThird.getFinalScore());
            baseMapper.updateFinalScoreByExpertIdAndThirdReviewItemId(updateThird);
        }
        return MsgUtil.success();
    }

    @Override
    public List<Long> findOrgIdListEliminate(Long sectionId, Long reviewItemId) {
        return baseMapper.findOrgIdListEliminate(sectionId, reviewItemId);
    }

    @Override
    public Boolean saveOrgEliminateStatus(Long sectionId, Long reviewItemId, List<Long> idList) {
        if (idList.size() > 0) {
            baseMapper.updateOrgEliminateStatus(sectionId, reviewItemId, idList);
        }

        return true;
    }

    @Override
    public Boolean cancelOrgEliminateStatus(Long sectionId, Long reviewItemId) {
        baseMapper.cancelOrgEliminateStatus(sectionId, reviewItemId);
        return true;
    }

}
